//
//  LOCarDetailViewController.m
//  renmingongshe
//
//  Created by macbook on 2017/11/1.
//  Copyright © 2017年 xiaodian. All rights reserved.
//

#import "LOCarDetailViewController.h"
#import "ShoppingCarDetailCell.h"
#import "HeaderView.h"
#import "FooterView.h"
#import "MineAddressViewController.h"
#import "LDPushOrderViewController.h"

@interface LOCarDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSInteger _allNum;
    NSInteger _allPrice;
    
    NSArray *_sections;
    
    NSDictionary *_address;
    NSMutableArray *_remarks;
    NSMutableArray *_shopids;
    
    BOOL _isSubmited;
}
@property(strong, nonatomic)UITableView *table;
@property (strong, nonatomic) UIView *headerView;
@property (weak, nonatomic) IBOutlet UILabel *totalPrice;
@end

@implementation LOCarDetailViewController
- (UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, WIDTH, HEIGHT-70-50) style:UITableViewStyleGrouped];
        _table.delegate = self;
        _table.dataSource = self;
        _table.tableHeaderView = self.headerView;
        
        [self.view addSubview:_table];
        
        [_table registerNib:[UINib nibWithNibName:@"ShoppingCarDetailCell" bundle:nil] forCellReuseIdentifier:@"ShoppingCarDetailCell"];
        [self.table registerClass:[FooterView class] forHeaderFooterViewReuseIdentifier:@"FooterView"];
        [self.table registerClass:[HeaderView class] forHeaderFooterViewReuseIdentifier:@"HeaderView"];
    }
    return _table;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 90)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleLabel.text = @"购物车详情";
    _sections = [NSArray array];
    _remarks = [NSMutableArray array];
    _shopids = [NSMutableArray array];
    
    if (self.payDic) {
        [self getQuickPayData];
    }else{
        [self getShoppingcarData];
    }
    
}
- (IBAction)PayClick:(UIButton*)sender {
    
    if (_isSubmited) {
        [self.view Message:@"已经提交过改订单"];
        return;
    }
    
    if (!_address.count) {
        [self.view Message:@"请填写收货地址"];
        return;
    }
    sender.enabled = NO;
    if (_payDic) {
        [self quickPay:sender];
    }else{
        [self shoppingcarPay:sender];
    }
    
}
- (void)quickPay:(UIButton *)sender
{
    NSMutableDictionary *para = [[NSMutableDictionary alloc]initWithDictionary:@{@"orderSrc":@"4",@"userToken":[Utils getUserToken],@"goodsId":_payDic[@"goodsId"],@"goodsSpecId":_payDic[@"goodsSpecId"],@"goodsNum":_payDic[@"goodsNum"],@"freight":_sections[0][@"freight"],@"s_addressId":_address[@"addressId"],@"remark_6":_remarks[0]}];
    
    [THWManager PostHttp:API(LOQuickPayClick) Parameters:para Success:^(id responseObject) {
        _isSubmited = YES;
        if (self.sucSubmit) {
            self.sucSubmit();
        }
        
        sender.enabled = YES;
        LDPushOrderViewController *order = [[LDPushOrderViewController alloc]init];
        order.loOrdernum = responseObject[@"data"];
        order.isLineOnOrder = YES;
        order.money = [NSString stringWithFormat:@"%ld",_allPrice];
        [self.navigationController pushViewController:order animated:YES];
        
    } andFalse:^(NSError *error) {
        sender.enabled = YES;
    }];
}
- (void)shoppingcarPay:(UIButton *)sender
{
    NSMutableDictionary *para = [[NSMutableDictionary alloc]initWithDictionary:@{@"orderSrc":@"4",@"userToken":[Utils getUserToken],@"addressId":_address[@"addressId"]}];
    
    for (int i=0; i<_remarks.count; i++) {
        [para setObject:_remarks[i] forKey:[NSString stringWithFormat:@
                                            "remark_%@",_shopids[i]]];
    }
    
    
    [THWManager PostHttp:API(LOCommitOrder) Parameters:para Success:^(id responseObject) {
        _isSubmited = YES;
        if (self.sucSubmit) {
            self.sucSubmit();
        }
        
        sender.enabled = YES;
        LDPushOrderViewController *order = [[LDPushOrderViewController alloc]init];
        order.loOrdernum = responseObject[@"data"][@"orderunique"];
        order.isLineOnOrder = YES;
        order.money = [NSString stringWithFormat:@"%ld",_allPrice];
        [self.navigationController pushViewController:order animated:YES];
        
    } andFalse:^(NSError *error) {
        sender.enabled = YES;
    }];
}
- (void)getQuickPayData
{
    [self.view loadingOnAnyView];
    NSDictionary *dic = @{@"userToken":[Utils getUserToken],@"goodsId":_payDic[@"goodsId"],@"goodsSpecId":_payDic[@"goodsSpecId"],@"goodsNum":_payDic[@"goodsNum"]};
    
    [THWManager PostHttp:API(LOQuickPay) Parameters:dic Success:^(id responseObject) {
        [self.view removeAnyView];
        NSDictionary *data = responseObject[@"data"];
        
        if (![String(responseObject[@"status_code"]) isEqualToString:@"1000"]) {
            
            [self.view Message:responseObject[@"msg"]];
            return;
        }
        
        NSDictionary *di = data[@"userAddress"];
        if ([di[@"areaName"]length]>0) {
            
            [self showAddressInfo:di];
        }else{
            UIButton* _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            _addBtn.frame = CGRectMake(54, (self.headerView.height-40)/2, WIDTH-108, 40);
            [_addBtn setBackgroundColor:[UIColor redColor]];
            [_addBtn setTitle:@"添加地址+" forState:UIControlStateNormal];
            _addBtn.layer.cornerRadius = 5.0;
            _addBtn.layer.masksToBounds = YES;
            [_addBtn addTarget:self action:@selector(AddClick) forControlEvents:UIControlEventTouchUpInside];
            [self.headerView addSubview:_addBtn];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, self.headerView.height-3, WIDTH, 3)];
            line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
            [self.headerView addSubview:line];
        }
        
 //       _allNum = [data[@"goodsNum"]integerValue];
//        _allPrice = [data[@"shopPrice"]integerValue];
//
//        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld 元",_allPrice];
//        NSMutableDictionary *carts= [[NSMutableDictionary alloc]initWithDictionary:data];
//        [carts setObject:@[data] forKey:@"list"];
//
//        _sections = @[carts];
        _allNum = [data[@"goodsNum"]integerValue];
        _allPrice = [data[@"goodsTotalMoney"]integerValue];
        
        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld 元",_allPrice];
    
        _sections = @[data];
            
        for (NSDictionary *d in _sections) {
            [_remarks addObject:@""];
            [_shopids addObject:d[@"shopId"]];
        }
        
        [self.table reloadData];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}
- (void)getShoppingcarData
{
    [self.view loadingOnAnyView];
    NSDictionary *dic = @{@"userToken":[Utils getUserToken],@"type":@"0",@"page_type":@"2",@"isSettlement":@"1"};
    
    [THWManager PostHttp:API(LOShoppingCarList) Parameters:dic Success:^(id responseObject) {
        [self.view removeAnyView];
        NSDictionary *data = responseObject[@"data"];
        
        if (![String(responseObject[@"status_code"]) isEqualToString:@"1000"]) {
    
            [self.view Message:responseObject[@"msg"]];
            return;
        }
        
        NSDictionary *di = data[@"userAddress"];
        if ([di[@"areaName"]length]>0) {
            
            [self showAddressInfo:di];
        }else{
            UIButton* _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            _addBtn.frame = CGRectMake(54, (self.headerView.height-40)/2, WIDTH-108, 40);
            [_addBtn setBackgroundColor:[UIColor redColor]];
            [_addBtn setTitle:@"添加地址+" forState:UIControlStateNormal];
            _addBtn.layer.cornerRadius = 5.0;
            _addBtn.layer.masksToBounds = YES;
            [_addBtn addTarget:self action:@selector(AddClick) forControlEvents:UIControlEventTouchUpInside];
            [self.headerView addSubview:_addBtn];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, self.headerView.height-3, WIDTH, 3)];
            line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
            [self.headerView addSubview:line];
        }
        
        _allNum = [data[@"goodsTotalNum"]integerValue];
        _allPrice = [data[@"goodsTotalMoney"]integerValue];
        
        _totalPrice.text = [NSString stringWithFormat:@"总计：%ld 元",_allPrice];
        NSDictionary *carts= data[@"carts"];
        if (carts.count > 0) {
            _sections = [carts allValues];
            
            for (NSDictionary *d in _sections) {
                [_remarks addObject:@""];
                [_shopids addObject:d[@"shopId"]];
            }
            
        }
        
        [self.table reloadData];
    } andFalse:^(NSError *error) {
        [self.view removeAnyView];
    }];
}
- (void)AddClick
{
    MineAddressViewController *edit = [[MineAddressViewController alloc] init];
    edit.address = ^(NSDictionary *dic) {
        
        [self showAddressInfo:dic];
    };
    [self.navigationController pushViewController:edit animated:YES];
}
- (void)showAddressInfo:(NSDictionary *)dic
{
    _address = dic;
    [self.headerView removeAllSubviews];
    
    UIImageView *ima = [[UIImageView alloc]initWithFrame:CGRectMake(10, 35, 20, 20)];
    ima.image = [UIImage imageNamed:@"LDStoreLocation"];
    [self.headerView addSubview:ima];
    
    UILabel *la = [[UILabel alloc]initWithFrame:CGRectMake(40, 20, WIDTH-80, 20)];
    la.font = [UIFont systemFontOfSize:14];
    la.text = [NSString stringWithFormat:@"收件人：%@          %@",dic[@"userName"],dic[@"userPhone"]];
    [self.headerView addSubview:la];
    
    UILabel *l = [[UILabel alloc]initWithFrame:CGRectMake(40, la.bottom+10, WIDTH-80, 20)];
    l.font = [UIFont systemFontOfSize:14];
    l.textColor = [UIColor grayColor];
    l.text = [NSString stringWithFormat:@"收货地址：%@ %@",dic[@"areaName"],dic[@"userAddress"]];
    [self.headerView addSubview:l];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, l.bottom+17, WIDTH, 3)];
    line.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [self.headerView addSubview:line];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:
                     CGRectMake(WIDTH-100, 0, 100, self.headerView.height)];
    [btn setTitle:@">" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 50, 0, 0)];
    [btn addTarget:self action:@selector(AddClick) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:btn];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _sections[section][@"list"];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *d = _sections[indexPath.section][@"list"][indexPath.row];
   
    ShoppingCarDetailCell *cell = [self.table dequeueReusableCellWithIdentifier:@"ShoppingCarDetailCell"];
    
    [cell cellConfig:d];
    if (self.payDic) {
        cell.num.text = [NSString stringWithFormat:@"数量 %ld",(long)_allNum];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *data = _sections[section];
    HeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HeaderView"];
    [header removeAllSubviews];
    UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    vi.backgroundColor = [UIColor whiteColor];
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, WIDTH-20, 50)];
    name.font = [UIFont boldSystemFontOfSize:14];
    [vi addSubview:name];
    [header addSubview:vi];
    
    name.text = data[@"shopName"];
    
    
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NSDictionary *data = _sections[section];
    
    FooterView *foot = [self.table dequeueReusableHeaderFooterViewWithIdentifier:@"FooterView"];
    UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 124)];
    vi.backgroundColor = [UIColor whiteColor];
    [foot addSubview:vi];
    
    UILabel *dispacth = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 20)];
    dispacth.text = @"配送方式";
    dispacth.font = [UIFont systemFontOfSize:13];
    [vi addSubview:dispacth];
    
    UILabel *la = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH-100, dispacth.mj_y, 90, dispacth.height)];
    la.text = [data[@"isFreeShipping"]integerValue]?@"包邮":[NSString stringWithFormat:@"邮费 %@ 元",data[@"freight"]];
    la.textAlignment = NSTextAlignmentRight;
    la.font = [UIFont systemFontOfSize:13];
    [vi addSubview:la];
    
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, dispacth.bottom+10, WIDTH, 0.5)];
    line1.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [vi addSubview:line1];
    
    UILabel *re = [[UILabel alloc]initWithFrame:CGRectMake(10, line1.bottom+10, 40, 20)];
    re.font = [UIFont systemFontOfSize:13];
    re.text = @"备注";
    [vi addSubview:re];
    
    UITextField *remark = [[UITextField alloc]initWithFrame:CGRectMake(re.right+10, re.mj_y, WIDTH-re.right-10-10, 20)];
    remark.placeholder = @"我的货要好一点的包装";
    remark.text = _remarks[section];
    remark.tag = section;
    remark.delegate = self;
    remark.font = [UIFont systemFontOfSize:13];
    [vi addSubview:remark];
    
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(0, remark.bottom+10, WIDTH, 0.5)];
    line2.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [vi addSubview:line2];
    
    UILabel *price = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH-60, line2.bottom+10, 50, 20)];
    price.text = [NSString stringWithFormat:@"￥%@",data[@"goodsMoney"]];
    price.font = [UIFont systemFontOfSize:13];
    price.textColor = [UIColor redColor];
    [vi addSubview:price];
    
    UILabel *num = [[UILabel alloc]initWithFrame:CGRectMake(price.mj_x-90, price.mj_y, 80, 20)];
    num.text = [NSString stringWithFormat:@"共%@件商品",data[@"shopGoodsNum"]] ;
    num.font = [UIFont systemFontOfSize:13];
    [vi addSubview:num];
    
    UIView *line3 = [[UIView alloc]initWithFrame:CGRectMake(0, num.bottom+10, WIDTH, 3)];
    line3.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    [vi addSubview:line3];
    
    if (self.payDic) {
        num.text =[NSString stringWithFormat:@"共%ld件商品",(long)_allNum];
        price.text = [NSString stringWithFormat:@"￥%ld",(long)_allPrice];
    }
    
    return foot;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 124;
}
- (void)textFieldDidEndEditing:(UITextField *)textField;
{
    [_remarks replaceObjectAtIndex:textField.tag withObject:textField.text];
}
-(void)keyboardWillShow:(NSNotification *)notificaiton
{
    CGRect keyboardFrame = [[notificaiton.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat keyboardHeight = keyboardFrame.size.height;
    self.table.height = HEIGHT-70-keyboardHeight;
    
}
-(void)keyboardWillHide:(NSNotification *)notificaiton
{
    self.table.height = HEIGHT-70-50;
    
}
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)removeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self addNotification];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [self removeNotification];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
